// 工具函数集合

/**
 * 存储相关工具函数
 */
export class StorageUtils {
  /**
   * 获取存储的数据
   */
  static async get<T>(key: string): Promise<T | null> {
    try {
      const result = await chrome.storage.sync.get([key]);
      return result[key] || null;
    } catch (error) {
      console.error(`Failed to get storage key "${key}":`, error);
      return null;
    }
  }

  /**
   * 设置存储的数据
   */
  static async set<T>(key: string, value: T): Promise<boolean> {
    try {
      await chrome.storage.sync.set({ [key]: value });
      return true;
    } catch (error) {
      console.error(`Failed to set storage key "${key}":`, error);
      return false;
    }
  }

  /**
   * 删除存储的数据
   */
  static async remove(key: string): Promise<boolean> {
    try {
      await chrome.storage.sync.remove([key]);
      return true;
    } catch (error) {
      console.error(`Failed to remove storage key "${key}":`, error);
      return false;
    }
  }

  /**
   * 清空所有存储数据
   */
  static async clear(): Promise<boolean> {
    try {
      await chrome.storage.sync.clear();
      return true;
    } catch (error) {
      console.error('Failed to clear storage:', error);
      return false;
    }
  }
}

/**
 * 消息传递工具函数
 */
export class MessageUtils {
  /**
   * 发送消息到背景脚本
   */
  static async sendToBackground(message: any): Promise<any> {
    try {
      return await chrome.runtime.sendMessage(message);
    } catch (error) {
      console.error('Failed to send message to background:', error);
      return null;
    }
  }

  /**
   * 发送消息到内容脚本
   */
  static async sendToContentScript(tabId: number, message: any): Promise<any> {
    try {
      return await chrome.tabs.sendMessage(tabId, message);
    } catch (error) {
      console.error('Failed to send message to content script:', error);
      return null;
    }
  }

  /**
   * 发送消息到所有标签页
   */
  static async sendToAllTabs(message: any): Promise<void> {
    try {
      const tabs = await chrome.tabs.query({});
      for (const tab of tabs) {
        if (tab.id) {
          try {
            await chrome.tabs.sendMessage(tab.id, message);
          } catch (error) {
            // 忽略无法发送消息的标签页
          }
        }
      }
    } catch (error) {
      console.error('Failed to send message to all tabs:', error);
    }
  }
}

/**
 * 标签页操作工具函数
 */
export class TabUtils {
  /**
   * 获取当前活动标签页
   */
  static async getActiveTab(): Promise<chrome.tabs.Tab | null> {
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      return tab || null;
    } catch (error) {
      console.error('Failed to get active tab:', error);
      return null;
    }
  }

  /**
   * 获取所有标签页
   */
  static async getAllTabs(): Promise<chrome.tabs.Tab[]> {
    try {
      return await chrome.tabs.query({});
    } catch (error) {
      console.error('Failed to get all tabs:', error);
      return [];
    }
  }

  /**
   * 创建新标签页
   */
  static async createTab(url: string, active: boolean = true): Promise<chrome.tabs.Tab | null> {
    try {
      return await chrome.tabs.create({ url, active });
    } catch (error) {
      console.error('Failed to create tab:', error);
      return null;
    }
  }

  /**
   * 关闭标签页
   */
  static async closeTab(tabId: number): Promise<boolean> {
    try {
      await chrome.tabs.remove(tabId);
      return true;
    } catch (error) {
      console.error('Failed to close tab:', error);
      return false;
    }
  }

  /**
   * 重新加载标签页
   */
  static async reloadTab(tabId: number): Promise<boolean> {
    try {
      await chrome.tabs.reload(tabId);
      return true;
    } catch (error) {
      console.error('Failed to reload tab:', error);
      return false;
    }
  }
}

/**
 * URL 处理工具函数
 */
export class UrlUtils {
  /**
   * 验证 URL 是否有效
   */
  static isValidUrl(url: string): boolean {
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  }

  /**
   * 获取域名
   */
  static getDomain(url: string): string {
    try {
      return new URL(url).hostname;
    } catch {
      return '';
    }
  }

  /**
   * 获取协议
   */
  static getProtocol(url: string): string {
    try {
      return new URL(url).protocol;
    } catch {
      return '';
    }
  }

  /**
   * 获取路径
   */
  static getPath(url: string): string {
    try {
      return new URL(url).pathname;
    } catch {
      return '';
    }
  }

  /**
   * 检查是否为 HTTPS
   */
  static isHttps(url: string): boolean {
    return this.getProtocol(url) === 'https:';
  }
}

/**
 * 通知工具函数
 */
export class NotificationUtils {
  /**
   * 显示基本通知
   */
  static async showBasic(
    title: string, 
    message: string, 
    iconUrl: string = 'icons/icon48.png'
  ): Promise<string | null> {
    try {
      return new Promise<string | null>((resolve) => {
        chrome.notifications.create({
          type: 'basic',
          iconUrl,
          title,
          message
        }, (notificationId) => {
          resolve(notificationId || null);
        });
      });
    } catch (error) {
      console.error('Failed to show notification:', error);
      return null;
    }
  }

  /**
   * 显示带按钮的通知
   */
  static async showWithButtons(
    title: string,
    message: string,
    buttons: chrome.notifications.ButtonOptions[],
    iconUrl: string = 'icons/icon48.png'
  ): Promise<string | null> {
    try {
      return new Promise<string | null>((resolve) => {
        chrome.notifications.create({
          type: 'basic',
          iconUrl,
          title,
          message,
          buttons
        }, (notificationId) => {
          resolve(notificationId || null);
        });
      });
    } catch (error) {
      console.error('Failed to show notification with buttons:', error);
      return null;
    }
  }

  /**
   * 清除通知
   */
  static async clear(notificationId: string): Promise<boolean> {
    try {
      return new Promise<boolean>((resolve) => {
        chrome.notifications.clear(notificationId, (wasCleared) => {
          resolve(wasCleared || false);
        });
      });
    } catch (error) {
      console.error('Failed to clear notification:', error);
      return false;
    }
  }
}

/**
 * 日期时间工具函数
 */
export class DateUtils {
  /**
   * 格式化日期时间
   */
  static formatDateTime(date: Date | number): string {
    const d = typeof date === 'number' ? new Date(date) : date;
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }

  /**
   * 格式化相对时间
   */
  static formatRelativeTime(date: Date | number): string {
    const d = typeof date === 'number' ? new Date(date) : date;
    const now = new Date();
    const diff = now.getTime() - d.getTime();
    
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    
    if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  }

  /**
   * 获取今天开始时间
   */
  static getStartOfToday(): Date {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return today;
  }

  /**
   * 获取今天结束时间
   */
  static getEndOfToday(): Date {
    const today = new Date();
    today.setHours(23, 59, 59, 999);
    return today;
  }
}

/**
 * 字符串工具函数
 */
export class StringUtils {
  /**
   * 截断字符串
   */
  static truncate(str: string, length: number, suffix: string = '...'): string {
    if (str.length <= length) {
      return str;
    }
    return str.substring(0, length - suffix.length) + suffix;
  }

  /**
   * 转义 HTML
   */
  static escapeHtml(str: string): string {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }

  /**
   * 移除 HTML 标签
   */
  static stripHtml(str: string): string {
    const div = document.createElement('div');
    div.innerHTML = str;
    return div.textContent || div.innerText || '';
  }

  /**
   * 检查是否为空字符串
   */
  static isEmpty(str: string | null | undefined): boolean {
    return !str || str.trim().length === 0;
  }

  /**
   * 生成随机字符串
   */
  static randomString(length: number = 8): string {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
}

/**
 * 性能监控工具函数
 */
export class PerformanceUtils {
  private static timers: Map<string, number> = new Map();

  /**
   * 开始计时
   */
  static startTimer(name: string): void {
    this.timers.set(name, performance.now());
  }

  /**
   * 结束计时并返回耗时
   */
  static endTimer(name: string): number {
    const startTime = this.timers.get(name);
    if (!startTime) {
      console.warn(`Timer "${name}" not found`);
      return 0;
    }
    
    const endTime = performance.now();
    const duration = endTime - startTime;
    this.timers.delete(name);
    
    return duration;
  }

  /**
   * 测量函数执行时间
   */
  static async measureAsync<T>(name: string, fn: () => Promise<T>): Promise<T> {
    this.startTimer(name);
    try {
      const result = await fn();
      const duration = this.endTimer(name);
      console.log(`${name} took ${duration.toFixed(2)}ms`);
      return result;
    } catch (error) {
      this.endTimer(name);
      throw error;
    }
  }
}